﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Model;
using SDT.Site.ViewModels;
using SDT.Lib.Common;
using System.Linq.Dynamic;
using SDT.Site.Properties;
using SDT.Lib.Paging;
using SDT.Systems;

namespace SDT.Site.Controllers
{
    [Authorize]
    public class MailController : Controller
    {
        private SDTDataContext db = new SDTDataContext();
        //
        // GET: /Mail/

        public ActionResult Register()
        {
            MailViewModels model = new MailViewModels();
            model.Categories = MailManager.GetListCategory();
            model.CatID = db.MailMembers.Where(e => e.AddBy == UserManager.GetUserId()).Select(e => e.CatID).ToList();
            var m = db.MailMembers.Where(e => e.AddBy == UserManager.GetUserId()).FirstOrDefault();
            model.ReceiveYN = m != null && m.ReceiveYN == true ? true : false;
            return View(model);
        }

        [HttpPost]
        public ActionResult Register(MailViewModels m)
        {

            try
            {
                UpdateModel(m);
                var l = new List<MailMember>();
                var u = UserManager.GetMember(UserManager.GetUserId(), true);
                if (u != null)
                {
                    foreach (int cid in m.CatID)
                    {
                        MailMember member = new MailMember();
                        member.AddBy = UserManager.GetUserId();
                        member.CatID = cid;
                        member.Email = u.Email;
                        member.ReceiveYN = true;
                        l.Add(member);
                    }
                    db.MailMembers.InsertAllOnSubmit(l);
                    db.SubmitChanges();
                    ViewData[Messages.MessageInfo] = Messages.INF_MAIL_001;
                }
                else {
                    ViewData[Messages.MessageInfo] = Messages.ERR_MAIL_002;
                }                
                m.Categories = MailManager.GetListCategory();
                m.ReceiveYN = l.Count>0 ? true : false;                
                return View(m);
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }
        public ActionResult Delete()
        {
            db.MailMembers.DeleteAllOnSubmit(from m in db.MailMembers where m.AddBy == UserManager.GetUserId() select m);
            db.SubmitChanges();
            return RedirectToAction("register");
        }
    }
}
